<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录 - 宠物家政服务</title>
    <link rel="stylesheet" href="styles/main.css">
    <link rel="stylesheet" href="styles/auth.css">
    <link rel="stylesheet" href="/styles/login-enhancements.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
    <header class="header">
        <div class="container">
            <div class="logo">
                <i class="fas fa-paw"></i>
                <span>宠物家政</span>
            </div>
            <nav class="nav">
                <a href="index.html" class="nav-link">首页</a>
                <a href="services.html" class="nav-link">服务预约</a>
                <a href="orders.html" class="nav-link">我的订单</a>
                <a href="profile.html" class="nav-link">个人中心</a>
            </nav>
            <div class="user-actions">
                <a href="login.html" class="btn btn-outline active">登录</a>
                <a href="register.html" class="btn btn-primary">注册</a>
            </div>
        </div>
    </header>

    <main class="main">
        <div class="auth-container">
            <div class="auth-card">
                <div class="auth-header">
                    <h1>欢迎回来</h1>
                    <p>登录您的账户以继续使用服务</p>
                </div>

                <!-- 登录方式切换 -->
                <div class="login-tabs">
                    <button class="tab-btn active" data-tab="password">账号密码登录</button>
                    <button class="tab-btn" data-tab="sms">手机验证码登录</button>
                </div>

                <!-- 账号密码登录 -->
                <form id="password-login" class="login-form active">
                    <div class="form-group">
                        <label for="username" class="form-label">用户名/手机号</label>
                        <div class="input-group">
                            <i class="fas fa-user"></i>
                            <input type="text" id="username" class="form-input" placeholder="请输入用户名或手机号" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="password" class="form-label">密码</label>
                        <div class="input-group">
                            <i class="fas fa-lock"></i>
                            <input type="password" id="password" class="form-input" placeholder="请输入密码" required>
                            <button type="button" class="toggle-password">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                    </div>

                    <div class="form-options">
                        <label class="checkbox-label">
                            <input type="checkbox" id="remember">
                            <span class="checkmark"></span>
                            记住我
                        </label>
                        <a href="forgot-password.html" class="forgot-link">忘记密码？</a>
                    </div>

                    <button type="submit" class="btn btn-primary btn-full" id="password-login-btn">
                        <span class="btn-text">登录</span>
                        <span class="btn-loading" style="display: none;">
                            <i class="fas fa-spinner fa-spin"></i> 登录中...
                        </span>
                    </button>
                </form>

                <!-- 手机验证码登录 -->
                <form id="sms-login" class="login-form">
                    <div class="form-group">
                        <label for="phone" class="form-label">手机号</label>
                        <div class="input-group">
                            <i class="fas fa-mobile-alt"></i>
                            <input type="tel" id="phone" class="form-input" placeholder="请输入手机号" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="sms-code" class="form-label">验证码</label>
                        <div class="input-group">
                            <i class="fas fa-shield-alt"></i>
                            <input type="text" id="sms-code" class="form-input" placeholder="请输入验证码" required>
                            <button type="button" class="send-sms-btn" id="send-sms">
                                <span class="sms-text">发送验证码</span>
                                <span class="sms-countdown" style="display: none;"></span>
                            </button>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary btn-full" id="sms-login-btn">
                        <span class="btn-text">登录</span>
                        <span class="btn-loading" style="display: none;">
                            <i class="fas fa-spinner fa-spin"></i> 登录中...
                        </span>
                    </button>
                </form>

                <div class="auth-footer">
                    <p>还没有账户？ <a href="register.html">立即注册</a></p>
                </div>

                <!-- 第三方登录 -->
                <div class="social-login">
                    <div class="divider">
                        <span>或使用以下方式登录</span>
                    </div>
                    <div class="social-buttons">
                        <button class="social-btn wechat" id="wechat-login">
                            <i class="fab fa-weixin"></i>
                            微信登录
                        </button>
                        <button class="social-btn qq" id="qq-login">
                            <i class="fab fa-qq"></i>
                            QQ登录
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <footer class="footer">
        <div class="container">
            <div class="footer-content">
                <div class="footer-section">
                    <h3>联系我们</h3>
                    <p><i class="fas fa-phone"></i> 400-123-4567</p>
                    <p><i class="fas fa-envelope"></i> service@petcare.com</p>
                </div>
                <div class="footer-section">
                    <h3>服务时间</h3>
                    <p>周一至周日 8:00-20:00</p>
                    <p>24小时在线客服</p>
                </div>
                <div class="footer-section">
                    <h3>关注我们</h3>
                    <div class="social-links">
                        <a href="#"><i class="fab fa-weixin"></i></a>
                        <a href="#"><i class="fab fa-weibo"></i></a>
                        <a href="#"><i class="fab fa-qq"></i></a>
                    </div>
                </div>
            </div>
            <div class="footer-bottom">
                <p>&copy; 2024 宠物家政服务. 保留所有权利.</p>
            </div>
        </div>
    </footer>

    <!-- 引入axios和API模块 -->
    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.0/dist/axios.min.js"></script>
    <script src="js/api.js"></script>
    
    <!-- 登录页面JavaScript -->
    <script>
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initLoginPage();
        });

        function initLoginPage() {
            // 初始化登录方式切换
            initLoginTabs();
            
            // 初始化密码显示/隐藏
            initPasswordToggle();
            
            // 初始化表单提交
            initFormSubmit();
            
            // 初始化验证码发送
            initSmsCode();
            
            // 初始化第三方登录
            initSocialLogin();
            
            // 检查是否有保存的登录信息
            checkRememberedLogin();
        }

        // 登录方式切换
        function initLoginTabs() {
            const tabBtns = document.querySelectorAll('.tab-btn');
            const loginForms = document.querySelectorAll('.login-form');

            tabBtns.forEach(btn => {
                btn.addEventListener('click', function() {
                    const targetTab = this.getAttribute('data-tab');
                    
                    // 更新按钮状态
                    tabBtns.forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    
                    // 更新表单显示
                    loginForms.forEach(form => {
                        form.classList.remove('active');
                        if (form.id === `${targetTab}-login`) {
                            form.classList.add('active');
                        }
                    });
                });
            });
        }

        // 密码显示/隐藏切换
        function initPasswordToggle() {
            const toggleBtn = document.querySelector('.toggle-password');
            const passwordInput = document.getElementById('password');

            if (toggleBtn && passwordInput) {
                toggleBtn.addEventListener('click', function() {
                    const type = passwordInput.type === 'password' ? 'text' : 'password';
                    passwordInput.type = type;
                    
                    const icon = this.querySelector('i');
                    icon.className = type === 'password' ? 'fas fa-eye' : 'fas fa-eye-slash';
                });
            }
        }

        // 表单提交处理
        function initFormSubmit() {
            // 账号密码登录
            const passwordForm = document.getElementById('password-login');
            if (passwordForm) {
                passwordForm.addEventListener('submit', handlePasswordLogin);
            }

            // 手机验证码登录
            const smsForm = document.getElementById('sms-login');
            if (smsForm) {
                smsForm.addEventListener('submit', handleSmsLogin);
            }
        }

        // 处理账号密码登录
        async function handlePasswordLogin(e) {
            e.preventDefault();
            
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();
            const remember = document.getElementById('remember').checked;
            
            // 表单验证
            if (!username || !password) {
                showMessage('请填写完整的登录信息', 'error');
                return;
            }

            // 显示加载状态
            const loginBtn = document.getElementById('password-login-btn');
            setButtonLoading(loginBtn, true);

            try {
                console.log("username, password", username, password);
                
                // 调用登录API
                const response = await petHouseAPI.auth.login({
                    username: username,
                    password: password
                });
                console.log("response", response)

                // 保存登录信息
                localStorage.setItem('token', response.data);
                localStorage.setItem('userInfo', JSON.stringify(response.user));
                
                // 如果选择记住我，保存用户名
                if (remember) {
                    localStorage.setItem('rememberedUsername', username);
                } else {
                    localStorage.removeItem('rememberedUsername');
                }

                showMessage('登录成功！正在跳转...', 'success');
                
                // 延迟跳转，让用户看到成功消息
                setTimeout(() => {
                    window.location.href = '/index.html';
                }, 1000);

            } catch (error) {
                console.error('登录失败:', error);
                showMessage(error.response?.data?.message || '登录失败，请检查用户名和密码', 'error');
            } finally {
                setButtonLoading(loginBtn, false);
            }
        }

        // 处理手机验证码登录
        async function handleSmsLogin(e) {
            e.preventDefault();
            
            const phone = document.getElementById('phone').value.trim();
            const smsCode = document.getElementById('sms-code').value.trim();
            
            // 表单验证
            if (!phone || !smsCode) {
                showMessage('请填写完整的登录信息', 'error');
                return;
            }

            // 手机号格式验证
            if (!/^1[3-9]\d{9}$/.test(phone)) {
                showMessage('请输入正确的手机号', 'error');
                return;
            }

            // 显示加载状态
            const loginBtn = document.getElementById('sms-login-btn');
            setButtonLoading(loginBtn, true);

            try {
                // 调用短信登录API
                const response = await petHouseAPI.auth.smsLogin({
                    phone: phone,
                    code: smsCode
                });

                // 保存登录信息
                localStorage.setItem('token', response.data);
                localStorage.setItem('userInfo', JSON.stringify(response.user));

                showMessage('登录成功！正在跳转...', 'success');
                
                // 延迟跳转
                setTimeout(() => {
                    window.location.href = '/index.html';
                }, 1000);

            } catch (error) {
                console.error('短信登录失败:', error);
                showMessage(error.response?.data?.message || '登录失败，请检查验证码', 'error');
            } finally {
                setButtonLoading(loginBtn, false);
            }
        }

        // 验证码发送
        function initSmsCode() {
            const sendSmsBtn = document.getElementById('send-sms');
            if (sendSmsBtn) {
                sendSmsBtn.addEventListener('click', handleSendSms);
            }
        }

        // 处理发送验证码
        async function handleSendSms() {
            const phone = document.getElementById('phone').value.trim();
            
            if (!phone) {
                showMessage('请输入手机号', 'error');
                return;
            }

            if (!/^1[3-9]\d{9}$/.test(phone)) {
                showMessage('请输入正确的手机号', 'error');
                return;
            }

            const sendSmsBtn = document.getElementById('send-sms');
            const smsText = sendSmsBtn.querySelector('.sms-text');
            const smsCountdown = sendSmsBtn.querySelector('.sms-countdown');

            try {
                // 调用发送验证码API
                await petHouseAPI.auth.sendSmsCode({
                    phone: phone,
                    type: 'login'
                });

                showMessage('验证码已发送，请注意查收', 'success');
                
                // 开始倒计时
                let countdown = 60;
                sendSmsBtn.disabled = true;
                smsText.style.display = 'none';
                smsCountdown.style.display = 'inline';
                
                const timer = setInterval(() => {
                    countdown--;
                    smsCountdown.textContent = `${countdown}s后重发`;
                    
                    if (countdown <= 0) {
                        clearInterval(timer);
                        sendSmsBtn.disabled = false;
                        smsText.style.display = 'inline';
                        smsCountdown.style.display = 'none';
                    }
                }, 1000);

            } catch (error) {
                console.error('发送验证码失败:', error);
                showMessage(error.response?.data?.message || '发送验证码失败，请重试', 'error');
            }
        }

        // 第三方登录
        function initSocialLogin() {
            const wechatBtn = document.getElementById('wechat-login');
            const qqBtn = document.getElementById('qq-login');

            if (wechatBtn) {
                wechatBtn.addEventListener('click', handleWechatLogin);
            }

            if (qqBtn) {
                qqBtn.addEventListener('click', handleQQLogin);
            }
        }

        // 微信登录
        async function handleWechatLogin() {
            try {
                // 调用微信登录API
                const response = await petHouseAPI.auth.wechatLogin();
                
                // 如果返回二维码URL，显示二维码
                if (response.qrCodeUrl) {
                    showQRCodeModal('微信登录', response.qrCodeUrl);
                } else {
                    // 直接登录成功
                    localStorage.setItem('token', response.data);
                    localStorage.setItem('userInfo', JSON.stringify(response.user));
                    window.location.href = '/index.html';
                }
            } catch (error) {
                console.error('微信登录失败:', error);
                showMessage('微信登录失败，请重试', 'error');
            }
        }

        // QQ登录
        async function handleQQLogin() {
            try {
                // 调用QQ登录API
                const response = await petHouseAPI.auth.qqLogin();
                
                if (response.qrCodeUrl) {
                    showQRCodeModal('QQ登录', response.qrCodeUrl);
                } else {
                    localStorage.setItem('token', response.data);
                    localStorage.setItem('userInfo', JSON.stringify(response.user));
                    window.location.href = '/index.html';
                }
            } catch (error) {
                console.error('QQ登录失败:', error);
                showMessage('QQ登录失败，请重试', 'error');
            }
        }

        // 显示二维码模态框
        function showQRCodeModal(title, qrCodeUrl) {
            const modal = document.createElement('div');
            modal.className = 'qr-modal';
            modal.innerHTML = `
                <div class="qr-modal-content">
                    <h3>${title}</h3>
                    <p>请使用手机扫描二维码登录</p>
                    <img src="${qrCodeUrl}" alt="登录二维码" class="qr-code">
                    <button class="btn btn-outline" onclick="this.parentElement.parentElement.remove()">关闭</button>
                </div>
            `;
            
            // 添加样式
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 1000;
            `;
            
            modal.querySelector('.qr-modal-content').style.cssText = `
                background: white;
                padding: 30px;
                border-radius: 10px;
                text-align: center;
                max-width: 300px;
            `;
            
            modal.querySelector('.qr-code').style.cssText = `
                width: 200px;
                height: 200px;
                margin: 20px 0;
            `;
            
            document.body.appendChild(modal);
        }

        // 检查记住的登录信息
        function checkRememberedLogin() {
            const rememberedUsername = localStorage.getItem('rememberedUsername');
            if (rememberedUsername) {
                document.getElementById('username').value = rememberedUsername;
                document.getElementById('remember').checked = true;
            }
        }

        // 设置按钮加载状态
        function setButtonLoading(button, loading) {
            const btnText = button.querySelector('.btn-text');
            const btnLoading = button.querySelector('.btn-loading');
            
            if (loading) {
                button.disabled = true;
                btnText.style.display = 'none';
                btnLoading.style.display = 'inline';
            } else {
                button.disabled = false;
                btnText.style.display = 'inline';
                btnLoading.style.display = 'none';
            }
        }

        // 显示消息提示
        function showMessage(message, type = 'info') {
            // 创建消息元素
            const messageEl = document.createElement('div');
            messageEl.className = `message message-${type}`;
            messageEl.textContent = message;
            
            // 添加样式
            messageEl.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 12px 20px;
                border-radius: 5px;
                color: white;
                font-weight: 500;
                z-index: 1000;
                animation: slideIn 0.3s ease;
                max-width: 300px;
            `;
            
            // 根据类型设置背景色
            const colors = {
                success: '#4caf50',
                error: '#f44336',
                warning: '#ff9800',
                info: '#2196f3'
            };
            messageEl.style.backgroundColor = colors[type] || colors.info;
            
            // 添加动画样式
            const style = document.createElement('style');
            style.textContent = `
                @keyframes slideIn {
                    from { transform: translateX(100%); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
                @keyframes slideOut {
                    from { transform: translateX(0); opacity: 1; }
                    to { transform: translateX(100%); opacity: 0; }
                }
            `;
            document.head.appendChild(style);
            
            document.body.appendChild(messageEl);
            
            // 3秒后自动移除
            setTimeout(() => {
                messageEl.style.animation = 'slideOut 0.3s ease';
                setTimeout(() => {
                    if (messageEl.parentNode) {
                        messageEl.parentNode.removeChild(messageEl);
                    }
                }, 300);
            }, 3000);
        }
    </script>
</body>
</html> 